package com.bx.implatform.growUp.service.Impl;


import com.bx.implatform.growUp.entity.VehicleTypeIncomeDay;
import com.bx.implatform.growUp.mapper.CollectFeeMapper;
import com.bx.implatform.growUp.service.CollectFeeService;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Slf4j
@Service
@RequiredArgsConstructor
public class CollectFeeServiceImpl implements CollectFeeService {

    @Resource
    private CollectFeeMapper collectFeeMapper;


    /**
     * 收费站流量 变化趋势
     *
     * @return
     */
    @Override
    public Map<String, List<Map<String, Object>>> getTrafficStats() {
        // 获取当前日期和12个月前的日期
        LocalDate now = LocalDate.now();
        LocalDate twelveMonthsAgo = now.minusMonths(11); // 包含当前月共12个月

        // 生成12个月的月份列表（格式：yyyy-MM）
        List<String> monthList = IntStream.range(0, 12)
                .mapToObj(i -> twelveMonthsAgo.plusMonths(i).format(DateTimeFormatter.ofPattern("yyyy-MM")))
                .toList();

        // 从数据库获取原始数据
        List<Map<String, Object>> mapList = collectFeeMapper.getTrafficStats();

        // 按公司分组
        Map<String, List<Map<String, Object>>> groupedData = mapList.stream()
                .collect(Collectors.groupingBy(
                        map -> Optional.ofNullable(map.get("group_key")).orElse("").toString(),
                        Collectors.mapping(
                                map -> {
                                    Map<String, Object> newMap = new HashMap<>(map);
                                    newMap.remove("group_key");
                                    return newMap;
                                },
                                Collectors.toList()
                        )
                ));

        // 为每个公司补全12个月数据
        Map<String, List<Map<String, Object>>> result = new LinkedHashMap<>();
        groupedData.forEach((company, dataList) -> {
            // 创建月份到数据的映射
            Map<String, Integer> monthToValue = dataList.stream()
                    .collect(Collectors.toMap(
                            map -> map.get("x").toString(),
                            map -> Integer.parseInt(map.get("y").toString())
                    ));

            // 为每个月份创建数据，缺失的补0
            List<Map<String, Object>> completeData = monthList.stream()
                    .map(month -> {
                        Map<String, Object> monthData = new HashMap<>();
                        monthData.put("x", month);
                        monthData.put("y", monthToValue.getOrDefault(month, 0));
                        return monthData;
                    })
                    .collect(Collectors.toList());

            result.put(company, completeData);
        });

        return result;
    }

    /**
     * 收费站收入 变化趋势
     *
     * @return
     */
    @Override
    public Map<String, List<Map<String, Object>>> getMoneyStats() {
        // 获取当前日期和12个月前的日期
        LocalDate now = LocalDate.now();
        LocalDate twelveMonthsAgo = now.minusMonths(11); // 包含当前月共12个月

        // 生成12个月的月份列表（格式：yyyy-MM）
        List<String> monthList = IntStream.range(0, 12)
                .mapToObj(i -> twelveMonthsAgo.plusMonths(i).format(DateTimeFormatter.ofPattern("yyyy-MM")))
                .toList();

        // 从数据库获取原始数据
        List<Map<String, Object>> mapList = collectFeeMapper.getMoneyStats();

        // 按公司分组
        Map<String, List<Map<String, Object>>> groupedData = mapList.stream()
                .collect(Collectors.groupingBy(
                        map -> Optional.ofNullable(map.get("group_key")).orElse("").toString(),
                        Collectors.mapping(
                                map -> {
                                    Map<String, Object> newMap = new HashMap<>(map);
                                    newMap.remove("group_key");
                                    return newMap;
                                },
                                Collectors.toList()
                        )
                ));

        // 为每个公司补全12个月数据
        Map<String, List<Map<String, Object>>> result = new LinkedHashMap<>();
        groupedData.forEach((company, dataList) -> {
            // 创建月份到数据的映射
            Map<String, Long> monthToValue = dataList.stream()
                    .collect(Collectors.toMap(
                            map -> map.get("x").toString(),
                            map -> Long.parseLong(map.get("y").toString())
                    ));

            // 为每个月份创建数据，缺失的补0
            List<Map<String, Object>> completeData = monthList.stream()
                    .map(month -> {
                        Map<String, Object> monthData = new HashMap<>();
                        monthData.put("x", month);
                        monthData.put("y", monthToValue.getOrDefault(month, 0L));
                        return monthData;
                    })
                    .collect(Collectors.toList());

            result.put(company, completeData);
        });

        return result;
    }

    /**
     * 客货流量变化趋势
     *
     * @return
     */
    @Override
    public List<Map<String, Object>> carFlow() {
        // 从数据库获取原始数据
        List<Map<String, Object>> list = collectFeeMapper.carFlow();
        return null;
    }
}
